package com.yoooya.base.admin.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @创建人 Sun Yijing
 * @创建时间 2018-06-28
 */
public class PermissionInterceptor extends HandlerInterceptorAdapter {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		SessionContext sessionContext = SessionContext
				.getSessionContext(request);
		//  =================跨域配置 start ==========
//		response.setHeader("Access-Control-Allow-Origin", "*");
//		response.setHeader("Access-Control-Allow-Credentials", "true");
//		response.setHeader("Access-Control-Allow-Methods", "*");
//		response.setHeader("Access-Control-Allow-Headers", "Authentication,Origin, X-Requested-With, Content-Type, Accept,token,x-token");
		response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
		response.setHeader("Access-Control-Allow-Methods", "*");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token,X-Token");

		///=================跨域配置 end ============

		/*LoginUser user = sessionContext.getUser();
		if (user == null || user.getUserId() == null) {
			logger.debug("收到来自[{}]的未授权命令[{}]请求.",
					WebUtils.getClientIp(request), request.getRequestURI());
			// response.setStatus(HttpServletResponse.SC_FORBIDDEN);
			// request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,
			// response);
			if (request.getRequestURI().lastIndexOf("api/") > 0) {
				return true;
			}
			if (request.getRequestURI().lastIndexOf("login") > 0) {
				return true;
			}
			if (request.getRequestURI().lastIndexOf("logout") > 0) {
				return true;
			}
			if (request.getRequestURI().lastIndexOf("main.html") > 0) {
				String targetUrl = request.getRequestURL().toString();
				if (StringUtils.isNotBlank(request.getQueryString())) {
					targetUrl += ("?" + request.getQueryString());
				}
				String contextPath = request.getContextPath();
				if (contextPath.equals("/")) {
					contextPath = "";
				}
				response.sendRedirect(contextPath + "/login.html");
				return false;
			}
			throw new ServiceException(1000, "登录超时，请重新登录。");

		}*/
		return true;
	}


}
